﻿using System;
using System.Collections.Generic;
using System.Json;
using System.Linq;
using ToodledoAPI.DataTypes;
using ToodledoAPI.Exceptions;

namespace ToodledoAPI
{
    public static class folders
    {
        public static void get(Key key, Action<Folder[]> returnAction)
        {
            string Method = String.Format("folders/get.php?key={0}", key);
            ApplicationConfiguration.CallWebService(Method, (s) =>
                {
                    if (s.IsToodledoException())
                    {
                        throw new folderException(s);
                    }
                    JsonArray Array = (JsonArray)JsonObject.Parse(s);
                    returnAction(Array.Select((F) => new Folder((JsonObject)F)).OrderBy((F)=>F.order).ToArray());

                });
        }

        public static void add(string name, bool isPrivate, Key key, Action<Folder> returnAction)
        {
            string Method = String.Format("folders/add.php?name={0};private={1};key={2}", name, isPrivate?1:0, key);
            ApplicationConfiguration.CallWebService(Method, (s) => {
                    if (s.IsToodledoException())
                    {
                        throw new folderException(s);
                    }
                    JsonArray Array = (JsonArray)JsonObject.Parse(s);
                    returnAction(new Folder((JsonObject)Array[0]));
            });
        }

        //todo:Add ability to edit folder

        public static void delete(int id, Key key, Action<int> returnAction_Success)
        {
            string Method = String.Format("folders/delete.php?id={0};key={1}", id, key);
            ApplicationConfiguration.CallWebService(Method, (s) =>
            {
                if (s.IsToodledoException())
                {
                    throw new folderException(s);
                }
                returnAction_Success(int.Parse(((JsonObject)JsonObject.Parse(s))["deleted"]));
            });
        }
    }
    namespace DataTypes
    {
        public class Folder
        {
            public Folder(JsonObject F)
            {
                id = int.Parse(F["id"]);
                name = F["name"];
                isPrivate = F["private"] == "1";
                isArchived = F["archived"] == "1";
                order = int.Parse(F["ord"]);
            }

            public int id { get; set; }
            public string name { get; set; }
            public bool isPrivate { get; set; }
            public bool isArchived { get; set; }
            public int order { get; set; }
        }
    }
}
